<template>
  <el-dialog
    v-model="visible"
    title="修改密码"
    width="400px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="当前密码" prop="currentPassword">
        <el-input
          v-model="form.currentPassword"
          type="password"
          show-password
          placeholder="请输入当前密码"
        />
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input
          v-model="form.newPassword"
          type="password"
          show-password
          placeholder="请输入新密码"
        />
      </el-form-item>
      <el-form-item label="确认新密码" prop="confirmPassword">
        <el-input
          v-model="form.confirmPassword"
          type="password"
          show-password
          placeholder="请再次输入新密码"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="submitForm" :loading="loading">确认修改</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { useAuthStore } from '../stores/auth'

export default {
  name: 'ChangePasswordDialog',
  props: {
    modelValue: Boolean
  },
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const visible = ref(false)
    const loading = ref(false)
    const formRef = ref(null)
    const authStore = useAuthStore()
    
    const form = reactive({
      currentPassword: '',
      newPassword: '',
      confirmPassword: ''
    })
    
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== form.newPassword) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }
    
    const rules = {
      currentPassword: [{ required: true, message: '请输入当前密码', trigger: 'blur' }],
      newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请确认新密码', trigger: 'blur' },
        { validator: validateConfirmPassword, trigger: 'blur' }
      ]
    }
    
    watch(() => props.modelValue, (val) => {
      visible.value = val
      if (val) {
        form.currentPassword = ''
        form.newPassword = ''
        form.confirmPassword = ''
      }
    })
    
    watch(visible, (val) => {
      emit('update:modelValue', val)
    })
    
    const handleClose = () => {
      formRef.value?.resetFields()
    }
    
    const submitForm = async () => {
      if (!formRef.value) return
      
      await formRef.value.validate(async (valid) => {
        if (valid) {
          loading.value = true
          try {
            await axios.put('/api/users/password', {
              currentPassword: form.currentPassword,
              newPassword: form.newPassword
            }, {
              headers: { Authorization: `Bearer ${authStore.token}` }
            })
            
            ElMessage.success('密码修改成功')
            visible.value = false
          } catch (error) {
            ElMessage.error(error.response?.data?.error || '修改失败')
          } finally {
            loading.value = false
          }
        }
      })
    }
    
    return {
      visible,
      loading,
      form,
      rules,
      formRef,
      handleClose,
      submitForm
    }
  }
}
</script>
